<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import { applyAddService, applySelectService, applyDeleteService, applyModifyService } from '@/api/apply';
import { matchSelectService } from '@/api/match';
import { userPageService } from "@/api/user.js";
import { teacherSelectService } from "@/api/teacher.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from "vue";
import moment from 'moment';

// 分页查询
const applyInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.applyId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
    load()
})
const handleCurrentChange = (val) => {
    pageNo.value = val
    load()
}
const handleSizeChange = (val) => {
    pageSize.value = val
    load()
}
const matchNameFuzzy = ref()
const userNameFuzzy = ref()
const teacherNameFuzzy = ref()
//发送分页查询请求（包括搜索功能）
const load = async () => {
    const res = await applySelectService(
        pageNo.value, pageSize.value, matchNameFuzzy.value, userNameFuzzy.value, teacherNameFuzzy.value
    )
    if (res.data.status === 'success') {
        applyInfo.value = res.data.data.list
        total.value = res.data.data.totalCount
        console.log(applyInfo.value)
    } else {
        ElMessage.error(res.data.info)
    }
}

/**
 * 添加报名信息
 */
//定义模态窗口变量和表格对象
const showAddModal = ref(false)
const applyInfoAddForm = ref({
    matchInfo: {
        matchId: '',
        matchName: ''
    },
    userInfo: {
        userId: '',
        userName: ''
    },
    costStatus: 0,
    applyTime: '',
    teacherInfo: {
        teacherId: '',
        teacherName: ''
    }
})
//  根据条件获取所有比赛信息
const matchList = ref([])
const currentMatchName = ref()
const matchLoading = ref(false)
const handleInputMatchChange = (query) => {
    matchLoading.value = true;
    setTimeout(() => {
        loadMatch(query)
        matchLoading.value = false;
    }, 1000);
}
const loadMatch = async (name) => {
    const res = await matchSelectService(1, 100000, name, '')
    matchList.value = res.data.data.list
}
const changeMatch = (matchInfo) => {
    if (!matchInfo) return
    applyInfoAddForm.value.matchInfo = matchInfo
}
//修改
const changeModifyMatch = (matchInfo) => {
    if (!matchInfo) return
    applyForm.value.matchInfo = matchInfo
}
//  根据条件获取所有队员信息
const userList = ref([])
const currentUserName = ref()
const userLoading = ref(false)
const handleInputUserChange = (query) => {
    userLoading.value = true;
    setTimeout(() => {
        loadUser(query)
        userLoading.value = false;
    }, 1000);
}
const loadUser = async (name) => {
    const res = await userPageService(1, 100000, '', name, '')
    userList.value = res.data.data.list
    console.log(userList.value)
}
const changeUser = (userInfo) => {
    if (!userInfo) return
    applyInfoAddForm.value.userInfo.userId = userInfo.userId
    applyInfoAddForm.value.userInfo.userName = userInfo.name
}
//修改
const changeModifyUser = (userInfo) => {
    if (!userInfo) return
    applyForm.value.userInfo.userId = userInfo.userId
    applyForm.value.userInfo.userName = userInfo.name
}
//  根据条件获取所有老师信息
const teacherList = ref([])
const currentTeacherName = ref()
const teacherLoading = ref(false)
const handleInputTeacherChange = (query) => {
    teacherLoading.value = true;
    setTimeout(() => {
        loadTeacher(query)
        teacherLoading.value = false;
    }, 1000);
}
const loadTeacher = async (name) => {
    const res = await teacherSelectService(1, 100000, name)
    teacherList.value = res.data.data.list
}
const changeTeacher = (teacherInfo) => {
    if (!teacherInfo) return
    applyInfoAddForm.value.teacherInfo = teacherInfo
}
const changeModifyTeacher = (teacherInfo) => {
    if (!teacherInfo) return
    applyForm.value.teacherInfo = teacherInfo
}
//打开模态窗口
const openAddModal = () => {
    //清空对象内容
    currentMatchName.value = ''
    currentUserName.value = ''
    currentTeacherName.value = ''
    applyInfoAddForm.value = {
        matchInfo: {
            matchId: '',
            matchName: ''
        },
        userInfo: {
            userId: '',
            userName: ''
        },
        costStatus: 0,
        applyTime: '',
        teacherInfo: {
            teacherId: '',
            teacherName: ''
        }
    }
    showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleFormModifyRef = ref()
const rules = {
    'matchInfo.matchName': [
        { required: true, message: '比赛名称不能为空', trigger: 'change' },
    ],
    costStatus: [
        { required: true, message: '缴费情况不能为空', trigger: 'change' },
    ],
    applyTime: [
        { required: true, message: '报名时间不能为空', trigger: 'change' },
    ],
    'userInfo.userName': [
        { required: true, message: '队员姓名不能为空', trigger: 'change' },
    ],
    'teacherInfo.teacherName': [
        { required: true, message: '指导老师不能为空', trigger: 'change' },
    ],
}
//格式化日期并渲染在表格上
const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
//发送添加报名请求
const addApplyInfo = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            // 解构 applyInfoAddForm.value 中的嵌套属性
            const {
                matchInfo: { matchId, matchName },
                userInfo: { userId, userName },
                applyTime,
                teacherInfo: { teacherId, teacherName }
            } = applyInfoAddForm.value;
            applyInfoAddForm.value.matchId = matchId
            applyInfoAddForm.value.matchName = matchName
            applyInfoAddForm.value.userId = userId
            applyInfoAddForm.value.userName = userName
            applyInfoAddForm.value.teacherId = teacherId
            applyInfoAddForm.value.teacherName = teacherName
            applyInfoAddForm.value.applyTime = moment(applyInfoAddForm.value.applyTime).format("YYYY-MM-DD HH:mm:ss");
            const res = await applyAddService(applyInfoAddForm.value)
            if (res.data.status === 'success') {
                ElMessage.success('添加报名成功')
                showAddModal.value = false
                await load()
            } else {
                ElMessage.error(res.data.info)
            }
        }
    })
}

/**
 * 修改报名信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改报名（弹出模态窗口）
//定义模态窗口变量和表格对象
const showModifyModal = ref(false)
const applyForm = ref({
    matchInfo: {
        matchId: '',
        matchName: ''
    },
    userInfo: {
        userId: '',
        userName: ''
    },
    costStatus: '',
    applyTime: '',
    teacherInfo: {
        teacherId: '',
        teacherName: ''
    }
})
const openModifyModal = (applyInfo) => {
    //将报名数据渲染到模态窗口的表格上面
    applyForm.value.matchInfo.matchId = applyInfo.matchId
    applyForm.value.matchInfo.matchName = applyInfo.matchName
    applyForm.value.userInfo.userId = applyInfo.userId
    applyForm.value.userInfo.userName = applyInfo.userName
    applyForm.value.costStatus = applyInfo.costStatus
    applyForm.value.applyTime = applyInfo.applyTime
    applyForm.value.applyTime = applyInfo.applyTime
    applyForm.value.teacherInfo.teacherId = applyInfo.teacherId
    applyForm.value.teacherInfo.teacherName = applyInfo.teacherName
    //打开模态窗口
    showModifyModal.value = true
}

//发送修改报名请求
const handleEdit = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            // 解构 applyForm.value 中的嵌套属性
            const {
                matchInfo: { matchId, matchName },
                userInfo: { userId, userName },
                applyTime,
                teacherInfo: { teacherId, teacherName }
            } = applyForm.value;
            applyForm.value.matchId = matchId
            applyForm.value.matchName = matchName
            applyForm.value.userId = userId
            applyForm.value.userName = userName
            applyForm.value.teacherId = teacherId
            applyForm.value.teacherName = teacherName
            applyForm.value.applyTime = moment(applyTime).format("YYYY-MM-DD HH:mm:ss");
            const res = await applyModifyService(applyForm.value)
            if (res.data.status === 'success') {
                await load()
                ElMessage.success('修改报名信息成功')
                showModifyModal.value = false
            } else {
                ElMessage.error(res.data.info)
            }
        }
    })
}

/**
 * 删除报名
 */
const openDeleteModal = (row) => {
    ElMessageBox.confirm(
        '确定要删除该报名吗?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await applyDeleteService(row.userId, row.matchId)
            if (res.data.status === 'success') {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败',
                })
            }
            await load()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
/**
 * 批量删除报名
 */
const opendeleteAllModal = () => {
    //非空判断
    if (selectIds.value == null) {
        ElMessage.info('未选中任何一名报名')
        return
    }
    if (selectIds.value != null && selectIds.value.length === 0) {
        ElMessage.info('未选中任何一名报名')
        return
    }
    //批量删除
    ElMessageBox.confirm(
        '确定要删除所有选中的报名吗?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await applyDeleteService(selectIds.value)
            if (res.data.status === 'success') {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败',
                })
            }
            load()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const getToken = () => {
    return localStorage.getItem('token')
}
</script>

<template>
    <!--  模态窗口-->
    <!--  修改成员信息模态窗口-->
    <div class="modify-modal" v-show="showModifyModal">
        <div class="modify-form">
            <div class="close-btn" @click="showModifyModal = false">&times;</div>
            <h1 style="text-align: center;font-size: 30px">修改报名信息</h1>
            <el-form :model="applyForm" ref="ruleFormModifyRef" :rules="rules" label-width="auto"
                style="max-width: 600px;margin: auto;margin-top: 50px">
                <el-form-item label="比赛名称">
                    <el-input disabled v-model="applyForm.matchInfo.matchName"
                        style="width: 240px" >
                    </el-input>
                </el-form-item>
                <el-form-item prop="costStatus" label="缴费情况">
                    <el-radio-group v-model="applyForm.costStatus">
                        <el-radio :value="0">未缴费</el-radio>
                        <el-radio :value="1">已缴费</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="applyTime" label="报名时间">
                    <div class="demo-datetime-picker">
                        <div class="block">
                            <el-date-picker v-model="applyForm.applyTime" type="datetime" placeholder="填写证书获得日期（可选）"
                                format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="队员名称"  :label-width="80">
                    <el-input disabled v-model="applyForm.userInfo.userName"
                        style="width: 240px"
                        >
                    </el-input>
                </el-form-item>

                <el-form-item label="指导老师" prop="teacherInfo.teacherName" :label-width="80">
                    <el-select v-model="applyForm.teacherInfo.teacherName" clearable placeholder="请查找并选择指导老师"
                        style="width: 240px" filterable :remote="true" :remote-method="handleInputTeacherChange"
                        @change="changeModifyTeacher" :loading="teacherLoading">
                        <el-option v-for="(item, index) in teacherList" :key="index" :label="item.teacherName"
                            :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item style="float: right">
                    <el-button type="primary" @click="handleEdit(ruleFormModifyRef)">修改</el-button>
                    <el-button @click="showModifyModal = false">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <!--  添加报名模态窗口-->
    <div class="modify-modal" v-show="showAddModal">
        <div class="modify-form">
            <div class="close-btn" @click="showAddModal = false">&times;</div>
            <h1 style="text-align: center;font-size: 30px">添加报名信息</h1>
            <el-form :model="applyInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
                style="max-width: 600px;margin: auto;margin-top: 50px">
                <el-form-item label="比赛名称" prop="matchInfo.matchName">
                    <el-select v-model="applyInfoAddForm.matchInfo.matchName" clearable placeholder="请查找并选择比赛名称"
                        style="width: 240px" filterable :remote="true" :remote-method="handleInputMatchChange"
                        @change="changeMatch" :loading="matchLoading">
                        <el-option v-for="(item, index) in matchList" :key="index" :label="item.matchName"
                            :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="costStatus" label="缴费情况">
                    <el-radio-group v-model="applyInfoAddForm.costStatus">
                        <el-radio :value="0">未缴费</el-radio>
                        <el-radio :value="1">已缴费</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="applyTime" label="报名时间">
                    <div class="demo-datetime-picker">
                        <div class="block">
                            <el-date-picker v-model="applyInfoAddForm.applyTime" type="datetime"
                                placeholder="填写证书获得日期（可选）" format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY"
                                time-format="HH:mm" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="队员名称" prop="userInfo.userName" :label-width="80">
                    <el-select v-model="applyInfoAddForm.userInfo.userName" clearable placeholder="请查找并选择队员名称"
                        style="width: 240px" filterable :remote="true" :remote-method="handleInputUserChange"
                        @change="changeUser" :loading="userLoading">
                        <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item" />
                    </el-select>
                </el-form-item>

                <el-form-item label="指导老师" prop="teacherInfo.teacherName" :label-width="80">
                    <el-select v-model="applyInfoAddForm.teacherInfo.teacherName" clearable placeholder="请查找并选择指导老师"
                        style="width: 240px" filterable :remote="true" :remote-method="handleInputTeacherChange"
                        @change="changeTeacher" :loading="teacherLoading">
                        <el-option v-for="(item, index) in teacherList" :key="index" :label="item.teacherName"
                            :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item style="float: right">
                    <el-button type="primary" @click="addApplyInfo(ruleFormRef)">添加</el-button>
                    <el-button @click="showAddModal = false">取消</el-button>
                </el-form-item>
            </el-form>

        </div>

    </div>


    <div>
        <!--    功能按钮-->
        <el-card style="width: 19%;margin-bottom: 30px;float: left">
            <el-button @click="openAddModal" type="primary">添加报名</el-button>
            <!-- <el-button @click="opendeleteAllModal" type="danger">批量删除</el-button> -->
        </el-card>
        <!--    搜索框-->
        <el-card class="member-search">
            <span style="margin-left: 10px">
                <h2>比赛名称：</h2>
            </span>
            <input v-model="matchNameFuzzy" @keyup.enter.native="load">
            <span style="margin-left: 10px">
                <h2>队员姓名：</h2>
            </span>
            <input v-model="userNameFuzzy" @keyup.enter.native="load">
            <span style="margin-left: 10px">
                <h2>老师姓名：</h2>
            </span>
            <input v-model="teacherNameFuzzy" @keyup.enter.native="load" style="border-right: none;">
            <el-button type="warning" @click="load">搜索</el-button>
        </el-card>
    </div>
    <div>
        <el-table ref="multipleTableRef" :data="applyInfo" stripe style="width: 100%;margin-top: 30px"
            @selection-change="handleSelectionChange">
            <el-table-column width="55" />
            <el-table-column property="matchName" label="比赛名称" width="150" />
            <el-table-column property="userName" label="队员姓名" width="150">
            </el-table-column>
            <el-table-column property="costStatus" label="缴费情况" width="150">
                <template #default="scope">
                    <div v-if="scope.row.costStatus === 0">未缴费</div>
                    <div v-if="scope.row.costStatus === 1">已缴费</div>
                </template>
            </el-table-column>
            <el-table-column property="applyTime" label="报名时间">
                <template #default="scope">
                    {{ formatDate(scope.row.applyTime) }}
                </template>
            </el-table-column>
            <el-table-column property="teacherName" label="指导老师" width="150" />
            <el-table-column property="updateTime" label="修改时间" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="info" @click="openModifyModal(scope.row)">
                        修改
                    </el-button>
                    <el-button size="small" type="danger" @click="openDeleteModal(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--    分页组件-->
        <el-card style="margin-top: 20px;float: right;">
            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
                    size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @current-change="handleCurrentChange" @size-change="handleSizeChange" />
            </div>
        </el-card>

    </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal {
    position: fixed;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: black;
    opacity: 1;
}

/*模态窗口表格样式*/
.modify-form {
    background-color: #ffffff;
    margin: 5% auto;
    /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    z-index: 10;
    border-radius: 10%;
    width: 30%;
    /* Could be more or less, depending on screen size */
}

.close-btn {
    cursor: pointer;
    color: #000000;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

/*搜索样式*/
.member-search {
    width: 80%;
    float: right
}

.member-search span {
    float: left;
}

.member-search input {
    float: left;
    height: 25px;
    border: solid 2px;
    margin-top: 2px;
}

/*表头样式*/
:deep() th.el-table__cell {
    color: black;
    font-size: 15px;
}
</style>
